package tech.dubbo.client.codec;

import com.fasterxml.jackson.databind.JavaType;
import com.fasterxml.jackson.databind.ObjectMapper;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.ByteToMessageDecoder;
import tech.dubbo.api.types.Request;
import tech.dubbo.api.types.Response;

import java.util.List;

/**
 * @ClassName
 * @Author niujie
 * @Version
 * @Description
 * @CreateTime 2024/10/6
 */
public class JsonDecoder<T> extends ByteToMessageDecoder {

    private final ObjectMapper objectMapper = new ObjectMapper();

    private final Class<T> clazz;

    public JsonDecoder(Class<T> clazz) {

        this.clazz = clazz;
    }

    @Override
    protected void decode(ChannelHandlerContext ctx, ByteBuf in, List<Object> out) throws Exception {

        byte[] bytes = new byte[in.readableBytes()];

        in.readBytes(bytes);

        JavaType requestType = objectMapper.getTypeFactory().constructParametricType(Response.class, clazz);

        Response<T> obj = objectMapper.readValue(bytes, requestType);

        out.add(obj);
    }
}
